import {
  webSocketUrl
} from '../config/network'
import localStorage from './localStorage'
//websocket 实体类
class webSocketClass {
  //构造器
  constructor() {
    this.url = webSocketUrl; //连接地址
    this.isCreate = false; // WebSocket 是否创建成功
    this.isConnect = false; // 是否已经连接
    this.isInitiative = false; // 是否主动断开
    this.timeoutNumber = 10 * 1000; // 心跳检测间隔
    this.heartbeatTimer = null; // 心跳检测定时器
    this.reconnectTimer = null; // 断线重连定时器
    this.socketExample = null; // websocket实例
    this.againTime = 20 * 1000 // 重连等待时间(单位毫秒)
  }
  // 初始化websocket连接
  initSocket() {
    const that = this
    this.socketExample = wx.connectSocket({
      url: that.url,
      timeout: 100000,
      header: {
        "Authorization": localStorage.get('Authorization')
      },
      success: () => {
        that.isCreate = true
      },
      fail: () => {
        that.isCreate = false
      }
    })
    this.createSocket()
  }
  // 创建websocket连接
  createSocket() {
    if (this.isCreate) {
      // 监听 WebSocket 连接打开事件
      try {
        this.socketExample.onOpen((res) => {
          this.isConnect = true
          // 发布事件
          wx.$emitter.emit("onOpen", true)
          clearInterval(this.heartbeatTimer)
          clearTimeout(this.reconnectTimer)
          // 打开心跳检测
          this.heartbeatCheck()
        })
        // 监听 WebSocket 接受到服务器的消息事件
        this.socketExample.onMessage((msg) => {
          const {
            data
          } = msg;
          if (data) {
            // 发布事件
            wx.$emitter.emit("onMessage", JSON.parse(data))
          }
        })
        // 监听 WebSocket 连接关闭事件
        this.socketExample.onClose(() => {
          this.isConnect = false
          console.log("连接关闭");
          this.reconnect()
        })
        // 监听 WebSocket 错误事件
        this.socketExample.onError(() => {
          this.isConnect = false
          this.isInitiative = false
        })
      } catch (error) {
        console.warn(error)
      }
    } else {
      console.warn('WebSocket 初始化失败!')
    }
  }
  // 发送消息
  sendMessage(message) {
    //没有连接则取消发送
    if(!this.isConnect) return;
    return new Promise((resolve, reject) => {
      this.socketExample.send({
        data: message,
        success() {
          resolve(true)
        },
        fail(error) {
          reject(error)
        }
      })
    })
  }
  // 开启心跳检测
  heartbeatCheck() {
    let heartbeatData = {
      dataType: "HEART_BEAT",
      time: new Date().valueOf(),
      id: localStorage.get("userInfo").id
    };
    this.heartbeatTimer = setInterval(() => {
      this.sendMessage(JSON.stringify(heartbeatData))
    }, this.timeoutNumber)
  }
  // 重新连接
  reconnect() {
    // 停止发送心跳
    clearTimeout(this.reconnectTimer)
    clearInterval(this.heartbeatTimer)
    // 如果主动关闭则不重连
    if (!this.isInitiative) {
      this.reconnectTimer = setTimeout(() => {
        this.initSocket()
      }, this.againTime)
    }
  }
  // 关闭 WebSocket 连接
  closeSocket() {
    const that = this
    return new Promise((resolve, reject) => {
      this.socketExample.close({
        success() {
          that.data = null
          that.isCreate = false
          that.isConnect = false
          that.isInitiative = true
          that.socketExample = null
          clearInterval(that.heartbeatTimer)
          clearTimeout(that.reconnectTimer)
          resolve(true);
        },
        fail() {
          reject(false);
        }
      })
    })
  }
}
//导出类
export default webSocketClass